<template>
	<view class="my-login">
		<view class="login-image">
			<uni-icons type="contact-filled" size="110" color="gray"></uni-icons>
		</view>
		<view class="login-button">
			<button @getuserinfo="getUserInfo" open-type="getUserInfo" class="btn-login">一键登录</button>
		</view>
		<view class="login-text">
			登录后尽享更多权益~
		</view>
	</view>
</template>

<script setup>
	import {useStore} from 'vuex';
	const store = useStore()
	// 点击一键登录获取用户信息
	function getUserInfo(e){
		 if (e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('您取消了登录授权！')
		store.commit('m_user/updateUserInfo',e.detail.userInfo)
		// 获取token
		getToken(e.detail)
	}
	// 获取token
	async function getToken(data){
		// 调用微信登录接口获得code字段
		const res = await uni.login().catch(err=>err)
		if(res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')
		// console.log('res', res,data)
		let query = {
			encryptedData: data.encryptedData,
			rawData: data.rawData,
			iv: data.iv,
			signature: data.signature,
			code:res.code
		}
		// console.log('query', query)
		const {data:tokenResult} = await uni.$http.post(uni.api.WX_LOGIN,query)
		// console.log('tokenResult',tokenResult)
		
		/* 虽然这里模拟不出来登陆成功 但是模拟一下从别的页面跳过来再重定向回去 */
		
		if(store.state.m_user.redirect && store.state.m_user.redirect.type == 'switchTab'){
			// console.log('store.state.m_user.redirect',store.state.m_user.redirect.from)
			let urlTo = store.state.m_user.redirect.from
			uni.switchTab({
				url:urlTo
			});
			store.commit('m_user/updateRedirect', null)
		}
		
		// 这个接口不能成功获取token
		if(tokenResult.meta.status!== 200)return uni.$showMsg('获取token失败！')
		store.commit('m_user/updateToken',tokenResult.message.token)
	}
</script>

<style lang="scss">
	page{
		background-color: #fff;
	}
	.my-login{
		display: flex;
		flex-direction: column;
		background-color: #efefef;
		height: 750rpx;
		width: 100%;
		justify-content: center;
		align-items: center;
		position: relative;
		overflow: hidden;
		.login-image{
			margin-bottom: 15px;
		}
		.login-button{
			width: 100%;
			margin-bottom: 15px;
			.btn-login{
				width: 70%;
				font-size: 16px;
				border-radius: 20px;
				background-color: #c00000;
				color: #fff;
			}
		}
		.login-text{
			font-size: 13px;
			color: gray;
		}
		&::after{
			content: '';
			position: absolute;
			background-color: #fff;
			width: 100%;
			height: 100rpx;
			border-radius: 100%;
			left: 0;
			bottom: -50rpx;
		}
	}
</style>